package com.gin.no_gay_alliance.fragment.topic;

import static com.gin.no_gay_alliance.enums.MessageWhat.ON_SUCCESS_FAVOR_FOLDER_EDIT;
import static com.gin.no_gay_alliance.enums.MessageWhat.OPEN_FAVOR_FOLDER;

import android.content.DialogInterface;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager2.widget.ViewPager2;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.params.nuke.favor.FavorDelParam;
import com.gin.nga.response.field.FavorFolder;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.adpter.FavorFolderAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.customview.PagerButton;
import com.gin.no_gay_alliance.databinding.FragmentTopicListFavorBinding;
import com.gin.no_gay_alliance.exception.RequireParamException;
import com.gin.no_gay_alliance.param.TopicListParam;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.viewmodel.TopicItem;

import java.util.List;
import java.util.Locale;
import java.util.Objects;

/**
 * 收藏夹
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/5 17:25
 **/
public class FavorFragment extends BaseTopicListFragment<FragmentTopicListFavorBinding> implements Callback<List<FavorFolder>> {
    public static final String TAG = FavorFragment.class.getSimpleName();
    /**
     * 是否允许修改收藏夹
     */
    private boolean editable;

    /**
     * 提供布局文件中的翻页按钮
     *
     * @return {@link PagerButton}
     */
    @NonNull
    @Override
    protected PagerButton initPagerButton() {
        return b.btnPager;
    }

    /**
     * 提供布局文件中的刷新按钮
     *
     * @return {@link ImageButton}
     */
    @NonNull
    @Override
    protected ImageButton initRefreshButton() {
        return b.btnRefresh;
    }

    /**
     * 提供布局文件中的 主题列表分页ViewPager2
     *
     * @return ViewPager2
     */
    @NonNull
    @Override
    protected ViewPager2 initViewPager2() {
        return b.vp2;
    }

    @Override
    protected void onCreateView() {
        super.onCreateView();


        if (param.authorUid == null && param.folderId == null) {
            throw new RequireParamException();
        }
        if (param.authorUid != null) {
            // 查询收藏夹列表
            favorFolderList(false);
        }
        // 是否允许修改收藏夹
        editable = Objects.equals(param.authorUid, MyApplication.getClient().getUserId());
        // 显示复选框
        showCheckBox = editable;
        // 提示信息
        b.tvFavorFolder.setText(String.format("点击切换%s", editable ? ", 长按修改" : ""));

        // 如果参数带有文件夹id，直接装载适配器
        if (param.folderId != null) {
            initAdapter(param);
        }
    }

    @Override
    public boolean handleMessage(@NonNull Message message) {
        if (message.what == OPEN_FAVOR_FOLDER.ordinal()) {
            // 打开收藏夹
            openFolder(((FavorFolder) message.obj).getId());
            return true;
        }
        if (message.what == ON_SUCCESS_FAVOR_FOLDER_EDIT.ordinal()) {
            favorFolderList(true);
            return true;
        }
        return super.handleMessage(message);
    }

    @Nullable
    @Override
    protected Toolbar initToolbar() {
        return b.toolbar;
    }


    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.favor_menu, menu);
    }

    /**
     * 点击选项按钮的操作
     *
     * @param item 选中的按钮
     * @return 是否消耗
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // 全选
        if (item.getItemId() == R.id.menu_item_check_all) {
            setAllChecked(true);
            return true;
        }
        // 全不选
        if (item.getItemId() == R.id.menu_item_uncheck_all) {
            setAllChecked(false);
            return true;
        }
        // 移除收藏
        if (item.getItemId() == R.id.menu_item_delete) {
            List<TopicItem> checkedItem = getCheckedItem();
            if (ObjectUtils.isEmpty(checkedItem)) {
                return true;
            }
            String message = String.format(Locale.CHINA, "即将移除 %d 个收藏", checkedItem.size());
            AlertDialogUtils.showConfirm(requireContext(), "移除收藏", message, (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    FavorDelParam p = new FavorDelParam(viewPager2.getCurrentItem() + 1);
                    checkedItem.forEach(i -> p.add(i.topicId, i.replyId != null ? i.replyId : 0));
                    // 移除收藏
                    MyApplication.app.managerFactory.getFavorManager().topicDel(p, data -> {
                        toast(data.getMessage());
                        //刷新当前页
                        ui(() -> b.btnRefresh.performClick());
                    });
                }
            });
            return true;
        }


        return super.onOptionsItemSelected(item);
    }

    /**
     * 查询收藏夹列表回调
     *
     * @param data 数据
     */
    @Override
    public void onSuccess(List<FavorFolder> data) {
        // 装载收藏夹
        if (!data.isEmpty()) {
            FavorFolderAdapter favorFolderAdapter = new FavorFolderAdapter(requireContext(), data);
            favorFolderAdapter.setEditable(editable);
            favorFolderAdapter.setHandler(handler);
            ui(() -> b.recyclerView.setAdapter(favorFolderAdapter));
            // 如果之前没有装载适配器,装载第一个列表
            if (adapter == null) {
                openFolder(data.get(0).getId());
            }
        } else {
            toast("该用户没有公开的收藏夹");
            // 关闭活动
            requireActivity().finish();
        }
    }

    /**
     * 查询收藏夹列表
     */
    private void favorFolderList(boolean ignoreCache) {
        MyApplication.app.managerFactory.getFavorManager().favorFolderList(ignoreCache, param.authorUid, this);
    }

    /**
     * 打开一个收藏夹
     *
     * @param id 收藏夹id
     */
    private void openFolder(long id) {
        TopicListParam p = new TopicListParam();
        p.type = TopicListParam.Type.FAVOR;
        p.folderId = id;
        ui(() -> {
            initAdapter(p);
        });
    }
}
